package com.meisen.springboot.service.impl;

import com.meisen.springboot.entity.IpWhiteList;
import com.meisen.springboot.repo.IpWhiteListRepository;
import com.meisen.springboot.service.IpWhiteListService;
import com.meisen.springboot.service.redis.IpWhiteListRedisService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Collection;
import java.util.List;
import java.util.stream.Collectors;

@Service
public class IpWhiteListServiceImpl implements IpWhiteListService {

    private final IpWhiteListRepository ipWhiteListRepository;
    private final IpWhiteListRedisService ipWhiteListRedisService;

    @Autowired
    public IpWhiteListServiceImpl(IpWhiteListRepository ipWhiteListRepository, IpWhiteListRedisService ipWhiteListRedisService) {
        this.ipWhiteListRepository = ipWhiteListRepository;
        this.ipWhiteListRedisService = ipWhiteListRedisService;
    }

    @Override
    public List<IpWhiteList> findAll() {
        List<IpWhiteList> whiteLists = ipWhiteListRedisService.getAll();
        if (isNullOrEmpty(whiteLists)) {
            whiteLists = ipWhiteListRepository.findAll();
            whiteLists.forEach(ipWhiteList -> ipWhiteListRedisService.put(ipWhiteList.getIp(), ipWhiteList, -1));
        }
        return whiteLists;
    }

    @Override
    public List<String> findAllIpWhite() {
        List<IpWhiteList> whiteLists = ipWhiteListRedisService.getAll();
        List<String> allIps = whiteLists.stream().map(IpWhiteList::getIp).collect(Collectors.toList());
        if (isNullOrEmpty(allIps)) {
            whiteLists = ipWhiteListRepository.findAll();
            allIps = whiteLists.stream()
                    .peek(ipWhiteList -> ipWhiteListRedisService.put(ipWhiteList.getIp(), ipWhiteList, -1))
                    .map(IpWhiteList::getIp)
                    .collect(Collectors.toList());
        }
        return allIps;
    }

    @Override
    public void addIpBlackList(IpWhiteList ipWhiteList) {
        ipWhiteListRepository.save(ipWhiteList);
        ipWhiteListRedisService.put(ipWhiteList.getIp(), ipWhiteList, -1);
    }

    @Override
    public void deleteIpWhiteList(String ip) {
        ipWhiteListRepository.deleteIpWhiteListByIp(ip);
        ipWhiteListRedisService.remove(ip);
    }

    @Override
    public void clearCache() {
        ipWhiteListRedisService.emptyHash();
    }

    private boolean isNullOrEmpty(Collection<?> collection) {
        return null == collection || collection.isEmpty();
    }
}
